package com.weareint.common.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.weareint.common.dto.IBasicDTO;
import com.weareint.common.entity.IBasicEntity;
import com.weareint.common.TokenProvider;
import com.weareint.common.vo.Result;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
public abstract class BasicController<T extends IBasicEntity<D>, D extends IBasicDTO> {

    protected Result<Void> deleteBatchIds(List<String> ids, HttpServletRequest request){
        if (log.isDebugEnabled()){
            Long currentUserId = getTokenProvider().getUserId(request);
            log.debug("ids = " + ids.toString() + ", currentUserId = " + currentUserId);
        }
        if (null == ids || ids.size() <= 0){
            return Result.error("参数不正确");
        }
        if (getService().removeByIds(ids)){
            return Result.ok();
        }
        return Result.error("批量删除失败");
    }

    protected Result<Void> doDeleteById(Long id, HttpServletRequest request){
        if (log.isDebugEnabled()){
            Long currentUserId = getTokenProvider().getUserId(request);
            log.debug("id = " + id + ", currentUserId = " + currentUserId);
        }
        if (null == id || id <= 0){
            return Result.error("参数不正确");
        }
        if (getService().removeById(id)){
            return Result.ok();
        }
        return Result.error("删除失败");
    }

    protected Result<D> doFindById(Long id){
        if(log.isDebugEnabled()){
            log.debug("id = " + id);
        }
        if (null == id || id <= 0){
            return Result.error("参数不正确");
        }
        T t = getService().getById(id);
        if (null == t){
            return Result.error("查询不到数据");
        }
        return Result.ok(t.toDTO());
    }

    protected abstract IService<T> getService();

    protected abstract TokenProvider getTokenProvider();
}
